package com.xysoft.admin.web;

import java.io.File;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Controller
@RequestMapping("/admin/upload.jspx")
public class FileUploadController {
	// 上传文件的保存的下一级路径，标示存储类型
	private static final String FOR_FILE_LOAD_DIR = "/file/pic/problem";
	// 系统默认建立和使用的以时间字符串作为文件名称的时间格式
	private static final String DEFAULT_SUB_FOLDER_FORMAT_AUTO = "yyyyMMdd";
	private static final String DEFAULT_SUB_FILE_FORMAT_AUTO = "yyyyMMddHHmmss";

	@RequestMapping(method = RequestMethod.GET)
	public void processUpload(ModelMap modelMap, HttpServletRequest request,
			HttpServletResponse response) {
		processUploadPost(modelMap, request, response);
		return;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void processUploadPost(ModelMap modelMap,
			HttpServletRequest request, HttpServletResponse response) {
		// 判断提交的请求是否包含文件
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (!isMultipart) {
			return;
		}
		try {
			// 上传文件的返回地址  
            String fileUrl = "";
			response.setContentType("text/html; charset=UTF-8");
			response.setHeader("Cache-Control", "no-cache");
			PrintWriter out = response.getWriter();

			MultipartHttpServletRequest mulrequest = (MultipartHttpServletRequest) request;
			CommonsMultipartFile file = (CommonsMultipartFile) mulrequest.getFile("upload");
			SimpleDateFormat formatFile = new SimpleDateFormat(DEFAULT_SUB_FILE_FORMAT_AUTO);
			String fileClientName = formatFile.format(new Date()) + getFileName(file.getOriginalFilename());
			String fileFix = StringUtils.substring(fileClientName,
					fileClientName.lastIndexOf(".") + 1);
			if (!StringUtils.equalsIgnoreCase(fileFix, "jpg")
					&& !StringUtils.equalsIgnoreCase(fileFix, "jpeg")
					&& !StringUtils.equalsIgnoreCase(fileFix, "bmp")
					&& !StringUtils.equalsIgnoreCase(fileFix, "gif")
					&& !StringUtils.equalsIgnoreCase(fileFix, "png")) {
				return;
			}
			String realPath = request.getSession().getServletContext().getRealPath(FOR_FILE_LOAD_DIR);
			SimpleDateFormat format = new SimpleDateFormat(DEFAULT_SUB_FOLDER_FORMAT_AUTO);
			String foldStr = format.format(new Date());
			realPath = realPath + File.separator + foldStr.substring(0, 4) + File.separator + foldStr.substring(4, 6) 
					+ File.separator + foldStr.substring(6, 8);
			fileUrl = ".." + FOR_FILE_LOAD_DIR + "/" + foldStr.substring(0, 4) + "/" 
					+ foldStr.substring(4, 6) + "/" + foldStr.substring(6, 8) + "/" + fileClientName;
			File realfile = new File(realPath);
			if (!realfile.exists()) {
				if (!realfile.mkdirs()) {
					return;
				}
			}
			String targetFilePath = realPath + "\\" + fileClientName;
			File targetFile = new File(targetFilePath);
			FileCopyUtils.copy(file.getBytes(), targetFile);
			//将上传的图片的url返回给ckeditor
			String callback = request.getParameter("CKEditorFuncNum");
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback
					+ ",'" + fileUrl + "','" + "上传成功！" + "')");
			out.println("</script>");
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return;
	}

	/**
	 * 获取文件扩展名 .
	 */
	private String getFileName(String str) {
		int index = str.lastIndexOf(".");
		if (-1 != index) {
			return str.substring(index);
		} else {
			return str;
		}
	}

}
